package com.wva.common.interceptor;

import com.wva.common.constant.LogConst;
import com.wva.common.context.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 日志上下文拦截器：从请求头取出traceId并放入MDC、将token放入MDC
 */
@Slf4j
public class LogContextInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //链路追踪
        String traceId = request.getHeader(LogConst.TRACE_ID_HEADER_NAME);
        MDC.put(LogConst.TRACE_ID_MDC_NAME, traceId);

        //登录用户
        if (UserContext.isLogin()) {
            MDC.put(LogConst.USER_MDC_NAME, String.valueOf(UserContext.getUserId()));
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        //渲染完毕后清除MDC上下文防止内存泄露
        MDC.clear();
    }
}
